﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Dynamic;
using System.Transactions;
using PagedList;
using Sovigaz.DataProvider;
using Utilities;

namespace Sovigaz.Permission.Repositories
{
    public class TestRepository : GenericRepository
    {
        public TestRepository()
            : base("TestID")
        {
        }

        public ICollection<TestComplex> Tests { get; set; }

        public void Delete(int id)
        {
            var item = GetByID(id);
            if (item != null)
                item.IsDeleted = true;

            _context.SaveChanges();
        }

        public void Delete(string[] idArr)
        {
            foreach (var id in idArr)
            {
                var item = GetByID(ConvertUtility.IntParse(id));
                if (item != null)
                    item.IsDeleted = true;
            }

            _context.SaveChanges();
        }

        public int Update(Test item)
        {
            var update = new Test();

            using (var scope = new TransactionScope())
            {
                if (item.TestID > 0)
                {
                    update = GetByID(item.TestID);
                    if (!Utility.ArrayEqual(update.Tstamp, item.Tstamp))
                        throw ExceptionHelper.CreateHttpResponseException("Dữ liệu đã bị cập nhật bởi người sử dụng khác.");
                }
                update.TestID = item.TestID;
                update.ProductID = item.ProductID;
                update.TestCode = item.TestCode;
                update.TestedDate = item.TestedDate;
                update.Enterprise = item.Enterprise;
                update.TestMachine = item.TestMachine;
                update.TestWeight = item.TestWeight;
                update.LostWeight = item.LostWeight;
                update.TestVolume = item.TestVolume;
                update.Result = item.Result;
                update.Description = item.Description;
                if (update.TestID == 0)
                    _context.Tests.Add(update);
                _context.SaveChanges();
                scope.Complete();
            }
            _context.Entry(update).Reload();
            var repository = new ProductRepository();
            Product product = repository.GetByID(update.ProductID);
                product.Status = update.Result;
                if (product.Status == ProductStatus.D.ToString())
                    product.Expired = update.TestedDate.AddYears(3);
                repository.Update(product);
                return update.TestID;
        }

        public Test GetByID(int id)
        {
            return _context.Tests.FirstOrDefault(p => p.TestID == id && !p.IsDeleted);
        }

        public TestRepository GetList(string whereClause, string orderBy, string orderDirection, int pageNumber)
        {
            var list = _context.Tests
                .Join(_context.Products,t=>t.ProductID,p=>p.ProductID,
                (t,p)=>new TestComplex
                    {
                        TestID=t.TestID,
                        ProductID=t.ProductID,
                        OwnerID=p.OwnerID,
                        Barcode=p.Barcode,
                        ProductCode=p.ProductCode,
                        TestCode=t.TestCode,
                        TestedDate=t.TestedDate,
                        Enterprise = t.Enterprise,
                        TestMachine = t.TestMachine,
                        TestWeight = t.TestWeight,
                        LostWeight = t.LostWeight,
                        TestVolume = t.TestVolume,
                        Result = t.Result,
                        IsDeleted = t.IsDeleted
                    })
                .Where(whereClause)
                .OrderBy(String.Format("{0} {1}", orderBy.Trim(), orderDirection.Trim()))
                .ToPagedList(pageNumber, DefaultPageSize);

            TotalItemCount = list.TotalItemCount;
            TotalItemOnPage = list.Count;
            PageCount = list.PageCount;
            PageNumber = list.PageNumber;
            Tests = list.ToList();

            return this;
        }
        
        public List<Test> GetListTest()
        {
            return _context.Tests.Where(p => !p.IsDeleted).ToList();
        }

        public int GetNextIndex()
        {
            if (_context.Tests.FirstOrDefault() == null) return 1;
            return _context.Tests.Max(p => p.TestID) + 1;
        }
    
    }
}
